package br.com.dufs.app.infra.hibernate;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import br.com.dufs.mvc.model.Usuario;

@Service("hibernateUserDetailsService")
public class HibernateUserDetailsService implements UserDetailsService {

		private SessionFactory sessionFactory;

		@Autowired
		public void setSessionFactory(SessionFactory sessionFactory) {
			this.sessionFactory = sessionFactory;
		}

		public SessionFactory getSessionFactory() {
			return sessionFactory;
		}

		@Autowired
		public HibernateUserDetailsService(SessionFactory sessionFactory) {
			setSessionFactory(sessionFactory);
		}

		@SuppressWarnings("unchecked")
		@Override
		@Transactional(readOnly = false)
		public UserDetails loadUserByUsername(String login) {
			Criteria criteria = getSessionFactory().getCurrentSession()
				.createCriteria(Usuario.class, "usuario");
			criteria.add(Restrictions.eq("usuario.login", login));
			List<Usuario> resultado = criteria.list();
			if (resultado != null && resultado.size() == 0) {
				throw new UsernameNotFoundException("Usuario nao encontrado!");
			}
			return (Usuario) resultado.get(0);
		}
}
